import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart' hide Action;
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/nav.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'state.dart';

Effect<PracticeEditState> buildEffect() {
  return combineEffects(<Object, Effect<PracticeEditState>>{
    Lifecycle.initState: _onInit,
    PracticeEditAction.onSubmit: _onSubmit,
  });
}

void _onInit(Action action, Context<PracticeEditState> ctx) async {
  // ocr photos
  var photos = ctx.state.photos;
  if (photos != null) {
    for (int i = 0; i < photos.length; i++) {
      ctx.dispatch(PracticeEditActionCreator.doingOcr(i));
      var photo = photos[i];
      var photoData = await photo.requestOriginal(quality: 80);
      HttpResult result = await Http.uploadPhoto("/publicUploadAction_upload",
          photoBuffer: photoData.buffer.asUint8List());
      if (result.success) {
        var ocr = {
          'title': result.data['articleTitle'].toString(),
          'content': result.data['articleWithoutTitle'].toString()
        };
        ctx.dispatch(PracticeEditActionCreator.doneOcr(ocr));
      } else {
        ctx.dispatch(PracticeEditActionCreator.doneOcr({}));
        Util.alertFail(result, ctx.context);
      }
    }
  }

  // get detail
  if (ctx.state.id.isNotEmpty) {
    ctx.dispatch(PracticeEditActionCreator.loading());
    HttpResult result =
        await Http.get("/correct/pub/api/write/detail.mvc", query: {
      'id': ctx.state.id,
      'ishomework': ctx.state.isHomework,
    });
    ctx.dispatch(PracticeEditActionCreator.loaded());

    if (result.success) {
      ctx.dispatch(PracticeEditActionCreator.result(result.data));
    } else {
      Util.alertFail(result, ctx.context);
    }
  }
}

void _onSubmit(Action action, Context<PracticeEditState> ctx) async {
  String title = ctx.state.titleEditController.text;
  String content = ctx.state.contentEditController.text;
  var type = ctx.state.typeValue;
  var grade = ctx.state.gradeValue;
  var userInfo = ctx.state.userInfo;

  if (title.isEmpty) {
    Util.alert('标题不能为空', ctx.context);
    return;
  }

  if (content.length < 15) {
    Util.alert('内容不能过短', ctx.context);
    return;
  }

  var starCount = content.length - content.replaceAll("*", "").length;
  if (starCount >= 30) {
    Util.alert('AI老师大约有$starCount个字符未识别，请校正后再批改，否则会影响分数哦！', ctx.context);
    return;
  }

  if (type == null || type.isEmpty) {
    Util.alert('请选择文体类型', ctx.context);
    return;
  }

  if (grade == null || grade.isEmpty) {
    Util.alert('请选择年级', ctx.context);
    return;
  }

  if (!Util.canUseAi(userInfo)) {
    bool ok =
        await Util.showConfirmDialog('会员已过期', '您的会员已过期，点击[确认]去充值', ctx.context);
    if (ok == true) {
      // 跳转去支付
      Navigator.of(ctx.context).pushNamed(Nav.PAY);
    }
    return;
  }

  Navigator.of(ctx.context).pushNamed(
    Nav.WEB_PAGE,
    arguments: {
      'url': '/correct/pub/anyone/view/machine/review.mvc',
      'share': false,
      'done': '完成',
      'postData': {
        "id": ctx.state.id,
        "title": title,
        "content": content,
        "grade": grade,
        "type": type
      }
    },
  ).then((done) {
    if (done == '完成') {
      Navigator.of(ctx.context)
          .pushNamedAndRemoveUntil(Nav.HOME, (Route<dynamic> route) => false);
    }
  });
}
